<?php

namespace common\models\member;

use Yii;
use common\models\user\UserBranch;
use common\helpers\Url;
use common\logics\ShareLogic;
use common\helpers\FileHelper;
use yii\base\Exception;

/**
 * This is the model class for table "{{%member}}".
 *
 * @property int $id
 * @property int $user_id 用户ID
 * @property int $type_id 会员类型ID
 * @property int $level_id 会员等级ID
 * @property string $scale 折扣比例
 * @property int $experience 经验值
 * @property int $expired_at 会员失效时间
 * @property string $qrcode 专属分享二维码
 * @property string $auth_token 安全校验TOKEN
 * @property int $audit_status 审核状态
 * @property int $audit_at 审核时间
 * @property string $audit_mark 审核备注
 * @property int $status 启用状态
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 * @property int $deleted_at 删除时间
 */
class Member extends \common\db\ActiveRecord {

    use \common\traits\User;

    //会员状态
    CONST STATUS_ACTIVE = 10;
    CONST STATUS_DEFAULT = 0;
    CONST STATUS_FORBID = -10;
    CONST STATUS_BLACK = -20;
    //审核状态
    CONST AUDIT_STATUS_FORBID = -2;
    CONST AUDIT_STATUS_REJECT = -1;
    CONST AUDIT_STATUS_DEFAULT = 0;
    CONST AUDIT_STATUS_SUBMIT = 1;
    CONST AUDIT_STATUS_ACCEPT = 2;
    CONST AUDIT_STATUS_ALLOW = 10;
    CONST AUDIT_STATUS_FINISH = 20;

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%member}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['user_id', 'type_id', 'level_id', 'experience', 'expired_at', 'audit_status', 'audit_at', 'status', 'created_at', 'updated_at', 'deleted_at'], 'integer'],
            [['scale'], 'number'],
            [['qrcode', 'auth_token', 'audit_mark'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'user_id' => '用户ID',
            'type_id' => '会员类型ID',
            'level_id' => '会员等级ID',
            'scale' => '折扣比例',
            'experience' => '经验值',
            'expired_at' => '会员失效时间',
            'qrcode' => '专属分享二维码',
            'auth_token' => '安全校验TOKEN',
            'audit_status' => '审核状态',
            'audit_at' => '审核时间',
            'audit_mark' => '审核备注',
            'status' => '启用状态',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
            'deleted_at' => '删除时间',
        ];
    }

    /**
     * 关联会员账户
     */
    public function getAccount() {
        return $this->hasOne(MemberAccount::className(), ['member_id' => 'id']);
    }

    /**
     * 关联会员基本资料信息
     */
    public function getType() {
        return $this->hasOne(MemberType::className(), ['id' => 'type_id']);
    }

    /**
     * 分销记录
     */
    public function getOrders() {
        return $this->hasMany(MemberMarketLog::className(), ['member_id' => 'id']);
    }

    /**
     * 分销记录数量
     */
    public function getOrderCount() {
        return (int) $this->getOrders()->count();
    }

    /**
     * 账户佣金变动日志
     */
    public function getAccountLogs() {
        return $this->hasMany(MemberAccountLog::className(), ['user_id' => 'user_id']);
    }

    /**
     * 账户佣金提现次数
     */
    public function getWithdrawCount() {
        return (int) $this->getAccountLogs()->andWhere(['balance' => MemberAccountLog::BALANCE_OUT])->count();
    }

    /**
     * 分销粉丝
     */
    public function getBranchs() {
        return $this->hasMany(UserBranch::className(), ['member_id' => 'id'])->andWhere([
            'status' => UserBranch::STATUS_ACTIVE,
        ]);
    }

    /**
     * 分销粉丝数
     */
    public function getDownerCount() {
        return (int) $this->getBranchs()->count();
    }

    /**
     * 关联会员基本资料信息
     */
    public function getLevel() {
        return $this->hasOne(MemberLevel::className(), ['id' => 'level_id']);
    }

    /**
     * 关联会员基本资料信息
     */
    public function getDefaultLevel() {
        return MemberLevel::find()->active()->orderBy(['level_no' => SORT_ASC])->one();
    }

    /**
     * 关联会员基本资料信息
     */
    public function getBond() {
        return $this->hasOne(MemberBond::className(), ['member_id' => 'id']);
    }

    /**
     * 关联会员基本资料信息
     */
    public function getData() {
        return $this->hasOne(MemberData::className(), ['member_id' => 'id']);
    }

    /**
     * 关联会员个人资料信息
     */
    public function getPersonal() {
        return $this->hasOne(MemberDataPersonal::className(), ['member_id' => 'id']);
    }

    public function getRealname() {
        return $this->data ? $this->data->realname : $this->user->nickname;
    }

    public function getAvatar() {
        return Url::attach($this->user->avatar);
    }

    /**
     * 会员权益
     */
    public function getPrivileges() {
        return MemberPrivilege::find()->active()->andWhere([
            'type_id' => [
                0, $this->type_id
            ],
        ])->orderBy([
            'type_id' => SORT_ASC,
            'listorder' => SORT_ASC
        ])->all();
    }

    /**
     * 黑名单
     */
    public function getIsBlack() {
        return $this->status === static::STATUS_BLACK;
    }

    /**
     * 是否有效会员
     */
    public function getIsAvaild() {
        return $this->audit_status === static::AUDIT_STATUS_FINISH && $this->status === static::STATUS_ACTIVE;
    }

    /**
     * 是否有效会员
     */
    public function hasActive() {
        return $this->isAvaild && $this->account;
    }

    /**
     * 会员申请中
     */
    public function getIsApplying() {
        return $this->audit_status !== static::AUDIT_STATUS_FINISH && $this->audit_status !== static::AUDIT_STATUS_FORBID && $this->status > 0;
    }

    /**
     * 是否被禁止会员申请
     */
    public function getIsForbid() {
        return $this->audit_status === static::AUDIT_STATUS_FORBID;
    }

    /**
     * 是否有效会员
     */
    public function getIsActive() {
        if ($this->audit_status == static::AUDIT_STATUS_FINISH) {
            return true;
        }
        return false;
    }

    /**
     * 是否有效会员
     */
    public function getIsFinish() {
        if ($this->audit_status == static::AUDIT_STATUS_FINISH && $this->status == static::STATUS_ACTIVE) {
            return true;
        }
        return false;
    }

    public function payment() {
        if ($this->audit_status == static::AUDIT_STATUS_ALLOW) {
            $this->audit_status = static::AUDIT_STATUS_FINISH;
        }
        $this->status = static::STATUS_ACTIVE;
        $level = $this->defaultLevel;
        if ($level) {
            $this->level_id = $level->id;
            $this->scale = $level->scale;
        }
        return $this->save();
    }

    /**
     * 会员权益
     */
    public function getAudit() {
        $data = [
            'status' => false,
            'text' => '',
            'mark' => $this->audit_mark,
            'time' => $this->audit_at,
        ];
        if ($this->audit_status == static::AUDIT_STATUS_FORBID) {
            $data['text'] = '未通过';
        } elseif ($this->audit_status == static::AUDIT_STATUS_REJECT) {
            $data['text'] = '补充资料';
        } elseif ($this->audit_status == static::AUDIT_STATUS_ALLOW) {
            $data['status'] = true;
            $data['text'] = '审核通过';
        } elseif ($this->audit_status == static::AUDIT_STATUS_DEFAULT) {
            $data['text'] = '等待审核';
        } elseif ($this->audit_status == static::AUDIT_STATUS_ACCEPT) {
            $data['text'] = '审核中';
        }
        return $data;
    }

    public static function findAvailable($condition) {
        $query = static::find()->active(static::STATUS_ACTIVE);
        $query->andWhere([
            'audit_status' => static::AUDIT_STATUS_FINISH
        ]);
        $query->andWhere($condition);
        return $query;
    }

    protected function generateQrcode() {
//        $share = ShareLogic::spread($this->user_id);
//        $data = $share['link'];

        $data = Url::h5('spread/invite/' . $this->user_id);

        $label = '';
        $logo = Yii::getAlias('@common/data/files/qrcode.jpg');
        $uploadPath = '@uploads';
        $relativeDir = '/attachments/member/' . date('Ym/d') . '/';
        $absoluteDir = Yii::getAlias($uploadPath . $relativeDir);
        FileHelper::dirCreate($absoluteDir);
//        $filename = FileHelper::generateUploadFileName('jpg');
        $filename = $this->id . '.jpg';
        $qrcodePath = $relativeDir . $filename;
        try {
            $qr = Yii::$app->qr->setText($data)
            ->setSize(300)
            ->setMargin(10);
            if ($label) {
                $qr = $qr->setLabel($label);
            }
            if ($logo) {
                $qr = $qr->setErrorCorrectionLevel(\Da\QrCode\Contracts\ErrorCorrectionLevelInterface::QUARTILE)->useLogo($logo)->setLogoWidth(84);
            }
            $qr->writeFile($absoluteDir . $filename);
            $this->qrcode = $qrcodePath;
            if (!$this->save()) {
                throw new Exception('二维码保存失败');
            }
        } catch (Exception $e) {
            return false;
        }
        return $qrcodePath;
    }

    public function getQrcodeUrl() {
        if (!$this->isAvaild) {
            return '';
        }
        $qrcode = $this->qrcode;
        if (!$qrcode) {
            $qrcode = $this->generateQrcode();
        }
        if ($qrcode) {
            return Url::attach($qrcode);
        }
        return '';
    }

}
